package com.bwie.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//@Configuration
public class MyFilter implements GlobalFilter, Ordered {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //获取变量
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();

        String url = request.getPath().toString();

        //设置白名单
        String ip = request.getRemoteAddress().getAddress().toString();

        if (ip.equals("192.168.11.131")) {
            //白名单全部放行
            return chain.filter(exchange);
        }

        //放行登录
        if (url.contains("/goods/goods/userLogin")) {
            return chain.filter(exchange);
        }


        //获取请求头的token
        String token = request.getHeaders().getFirst("token");

        if (token==null) {
            System.out.println("未登录必须拦截"+url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //解析token
        Claims bwie = Jwts.parser().setSigningKey("bwie")
                .parseClaimsJws(token)
                .getBody();

        Integer userId = bwie.get("id", Integer.class);

        String key="TOKEN-"+userId;

        String redisToken = stringRedisTemplate.opsForValue().get(key);

        if (redisToken==null) {
            System.out.println("token过期了"+url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        if (!redisToken.equals(token)) {
            System.out.println("异地登录了"+url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //全部放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
